package cn.wolfcode.service.impl;

import cn.wolfcode.domain.MemberNews;
import cn.wolfcode.domain.News;
import cn.wolfcode.mapper.MemberNewsMapper;
import cn.wolfcode.mapper.NewsMapper;
import cn.wolfcode.qo.NewsObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INewsService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NewsServiceImpl implements INewsService {

    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private MemberNewsMapper memberNewsMapper;


    @Override
    public void save(News news) {
        news.setCreationtIme(new Date());
        news.setEmployee(UserContext.getCurrentUser());
        //给属性设置默认值
        news.setStatuss(false);
        news.setIsRead(false);
        newsMapper.insert(news);
        //在公告插入的同时,把中间表的数据插入进去
        MemberNews memberNews = new MemberNews();
        memberNews.setNewsId(news.getId());
        memberNews.setEmployeeId(news.getId());
        memberNewsMapper.insert(memberNews);
    }

    @Override
    public void delete(Long id) {
        newsMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(News news) {

        newsMapper.updateByPrimaryKey(news);
    }

    @Override
    public News get(Long id) {
        return newsMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<News> listAll() {
        return newsMapper.selectAll();
    }

    @Override
    public PageInfo<News> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize()); //对下一句sql进行自动分页
        List<News> newss = newsMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<News>(newss);
    }

    @Override
    public PageInfo selectList(NewsObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize()); //对下一句sql进行自动分页
        //这个方法是用来判断是否是管理员,如果是那就返回所有的,如果不是那就返回未发布的
        return new PageInfo<News>(newsMapper.selectList(qo));
    }

    @Override
    public void updateOne(Long id) {
        newsMapper.updateOne(id,true);
    }

    @Override
    public void updateisRead(Long id) {
        newsMapper.updateisRead(id,true);
    }
}
